<template>
  <p>
    <a-space>
      <a-button type="primary" @click="handleQuery()">刷新</a-button>
      <a-button type="primary" @click="onAdd">新增</a-button>
    </a-space>
  </p>
  <a-table :dataSource="passengers"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-popconfirm
              title="删除后不可恢复，确认删除?"
              @confirm="onDelete(record)"
              ok-text="确认" cancel-text="取消">
            <a style="color: red">删除</a>
          </a-popconfirm>
          <a @click="onEdit(record)">编辑</a>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'type'">
        <span v-for="item in PASSENGER_TYPE" :key="item.code">
          <span v-if="item.code === record.type">
            {{ item.desc }}
          </span>
        </span>
      </template>
    </template>
  </a-table>
  <a-modal v-model:visible="visible" title="乘车人" @ok="handleOk"
           ok-text="确认" cancel-text="取消">
    <a-form :model="passenger" :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
      <a-form-item label="姓名">
        <a-input v-model:value="passenger.name"/>
      </a-form-item>
      <a-form-item label="身份证">
        <a-input v-model:value="passenger.idCard"/>
      </a-form-item>
      <a-form-item label="旅客类型">
        <a-select v-model:value="passenger.type">
          <a-select-option v-for="item in PASSENGER_TYPE" :key="item.code" :value="item.code">
            {{ item.desc }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts" name="Passenger">
import {ref, onMounted} from 'vue';
import {notification} from "ant-design-vue";
import {deleteById, queryList, save} from "@/api/passenger";
import {QueryParams, QueryResArray, SaveParams} from "@/api/passenger/type.ts";
import {PASSENGER_TYPE} from "@/enums/PassengerType.ts";
import {copyObj} from "@/utils/tools.ts";

// Refs
const visible = ref(false);
const passenger = ref<SaveParams>({
  name: "",
  idCard: "",
  type: ""
});
const passengers = ref<QueryResArray>([]);
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 15,
});
const loading = ref(false);

// Columns definition
const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '身份证',
    dataIndex: 'idCard',
    key: 'idCard',
  },
  {
    title: '旅客类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];

// Methods
const onAdd = () => {
  passenger.value = {idCard: "", name: "", type: ""};
  visible.value = true;
};

const onEdit = (record: any) => {
  passenger.value = copyObj(record)
  visible.value = true;
};

const onDelete = async (record: any) => {
  try {
    const response = await deleteById(record.id);
    if (response.success) {
      notification.success({message: "提示", description: "删除成功!"});
      await handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
      });
    } else {
      notification.error({message: "删除失败", description: response.message});
    }
  } catch (error) {
    console.error('Error deleting passenger:', error);
  }
};

const handleOk = async () => {
  try {
    const result = await save(passenger.value);
    if (result.success) {
      notification.success({message: "操作成功！", description: "保存成功!"});
      visible.value = false;
      await handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize,
      });
    } else {
      notification.error({message: result.message, description: result.message});
    }
  } catch (error) {
    console.error('Error saving passenger:', error);
  }
};

const handleQuery = async (param: QueryParams) => {
  loading.value = true;
  param = param || {
    pageNum: 1,
    pageSize: pagination.value.pageSize,
  }
  try {
    const response = await queryList(param);
    loading.value = false;
    if (response.success) {
      passengers.value = response.data;
      pagination.value.current = param.pageNum as number;
      pagination.value.total = response.total;
    } else {
      notification.error({message: "查询失败", description: response.message});
    }
  } catch (error) {
    console.error('Error querying passengers:', error);
  }
}

const handleTableChange = (pagination: any) => {
  handleQuery({
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  });
};

// On mounted hook
onMounted(async () => {
  const param: QueryParams = {
    pageNum: 1,
    pageSize: pagination.value.pageSize,
  }
  await handleQuery(param);
});

// Expose variables and functions to template
defineExpose({
  PASSENGER_TYPE,
  passenger,
  visible,
  passengers,
  pagination,
  columns,
  handleTableChange,
  handleQuery,
  loading,
  onAdd,
  handleOk,
  onEdit,
  onDelete,
});
</script>
